package org.xukai.common.Proxy;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;

public class DynamicClassLoader extends URLClassLoader {

	public DynamicClassLoader(ClassLoader parentClassLoader) {
		super(new URL[0], parentClassLoader);
	}

	public Class<?> defineClassByByteArray(String className , byte[]bytes) {
		return this.defineClass(className , bytes, 0, bytes.length);
	}

	public static void main(String[] args) throws ClassNotFoundException {
		System.out.println(5/3);
//		DynamicClassLoader loader = new DynamicClassLoader(DynamicClassLoader.class.getClassLoader());
//		Class<?> aClass = loader.defineClassByByteArray("org.xukai.common.MyList", readFinal
//				("E:\\IDEA_workSpace\\coding2017\\group19\\527220084\\xukai_coding\\coding-common\\target\\classes" +
//						"\\org\\xukai\\common\\MyList.class"));
//		FileSystemClassloader classloader = new FileSystemClassloader("E:\\IDEA_workSpace\\coding2017\\group19\\527220084\\xukai_coding\\coding-common\\target\\classes");
//		Class<?> aClass = classloader.loadClass("org.xukai.common.MyList");
//		try {
//			try {
//				Object o = aClass.newInstance();
//				System.out.println(aClass.getClassLoader());
//				Method add = aClass.getDeclaredMethod("add");
//				add.invoke(o);
//			} catch (InstantiationException e) {
//				e.printStackTrace();
//			} catch (IllegalAccessException e) {
//				e.printStackTrace();
//			}
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
	}

	public static byte[] readFinal(String path) {
		try {
			FileInputStream in = new FileInputStream(path);
			ByteArrayOutputStream out = new ByteArrayOutputStream();
			byte[] buf = new byte[1024];
			int len = 0;
			while((len = in.read(buf)) != -1){
				out.write(buf,0,len);
			}
			return out.toByteArray();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
}
